package commands.base {
	
	import devkit.commando.ICustomCommand;
	import devkit.commando.rpc.RPCBase;
	
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	
	/**
	 * Command to log a user on to the system.
	 * @author Francois Dempers
	 */
	public class LoginUser extends RPCBase implements ICustomCommand {
		
		public var userName:String;
		public var password:String;
		
		/**
		 * Creates a new <code>LoginUser</code> command.
		 * @param handler The function to invoke when a result is received.
		 */
		public function LoginUser(handler:Function) {
			
			super(Session.rpcGateway, "groupSite.Base", handler);
		}
		
		/**
		 * Validates all of the command arguments.
		 * @return <code>null</code> if the command was executed, otherwise an error code or message.
		 */
		public function validate():String {
			
			if(userName == null || userName.length < 6) {
				return "User name too short"; // User name must be more than 6 characters
			} else if(password == null || password.length < 6) {
				return "Password too short"; // Password must be more than 6 characters
			}
			return null;
		}
		
		/**
		 * Executes the command.
		 * @return <code>null</code> if the command was executed, otherwise an error code or message.
		 */
		public function execute():String {
			
			var error:String = validate();
			if(error != null) {
				return error;
			}
			
			invoke("loginUser", userName, password);
			
			return null;
		}
		
		/**
		 * Called when a result is received from the service.
		 * @param event The result event.
		 */
		public function result(event:ResultEvent):void {
			
			var myResult:Object = event.result as Object;
			
			dispatchResult(myResult);
		}
		
		/**
		 * Called when a fault is received from the service.
		 * @param event The fault event.
		 */
		public function fault(event:FaultEvent):void {
			
			dispatchFault(HANDLE_BOTH, event);
		}
	}
}